package wang.chunfan.code.netty.bio;

import java.io.*;
import java.net.Socket;
import java.util.Date;

/**
 * @version 1.0
 * @Author wangchunfan
 * @Date 2020/5/29 17:07
 **/
public class TimeServerHandler implements Runnable {
    private Socket socket;

    public TimeServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
             PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true)) {

            String currentTime = null;
            String body = null;
            while (true) {
                body = in.readLine();
                if (body == null) {
                    break;  // 读到输入流尾部直接跳出循环
                }
                System.out.println("The time server receiver order:" + body);
                // 判断是否为获取最新事件的请求
                currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
                out.println(currentTime);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (this.socket != null) {
                try {
                    this.socket.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            this.socket = null;
        }
    }
}
